<?php

namespace App\Http\Controllers;

use App\Jobs\CloseOrder;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Interfaces\GoodsService;
use App\Interfaces\CartService;
use App\Interfaces\OrderService;
use App\Exceptions\Interfaces\CartServiceException;


use App\Good;

// use Illuminate\Support\Facades\Auth;
// use Illuminate\Support\Facades\Log;
use InvalidArgumentException;
use Session, Auth, Log;

class CartController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(CartService $cartService)
    {

        $cart = $cartService->getInfo();

        // dd($cart);

        // return view('mobile.cart.index',['cart'=>$cart]);

        return view('mobile.cart.index', compact('cart'));
    }


    /**
     * 结算购物车
     * 下订单
     * @return \Illuminate\Http\Response
     */
    public function settlement(OrderService $orderService, CartService $cartService, Request $request)
    {
        $goods_ids=$request->goods_ids;
        //查询购物车商品
        $cartInfo = $cartService->getInfo($goods_ids);
        //创建订单
        $orderPay= $orderService->createOrder($cartInfo);
        $this->dispatch(new CloseOrder($orderPay,config('app.order_ttl')));
        //清空购物车
        $cartService->deleteCartGoods($goods_ids);
        return Response()->json([
            'code'=>1,
            'message'=>'订单创建成功，前往支付',
            'orderId'=>$orderPay->order_pay_id,
        ]);

    }//end func settlement


    /**
     * 快速结算
     *
     * @return \Illuminate\Http\Response
     */
    public function fastSettlement(OrderService $orderService, Request $request)
    {
        $user = Auth::user();
        $goods_id = $request->get('goods_id');
        $buy_num = $request->num;
        $good = Good::findOrFail($goods_id)->toArray();

        $price = $user->is_recharge == 1 ? $good['repeat_price'] : $good['cost_price'];
        $good['goods_id'] = $goods_id;
        $good['buy_num'] = $buy_num;
        $cartInfo = [
            'price' => $price * $buy_num,
            'cartGoods' => [$good]
        ];

        $orderPay=$orderService->createOrder($cartInfo);
        //队列关闭订单
        $this->dispatch(new CloseOrder($orderPay,config('app.order_ttl')));
       // dd($orderPay);
        return Response()->json([
            'code'=>1,
            'message'=>'订单创建成功，前往支付',
            'orderId'=>$orderPay->order_pay_id,
        ]);

    }//end func fastSettlement


    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request, CartService $cartService)
    {

        // dd($request->all());

        $return = ['message' => '', 'code' => 0];
        $goods_id = $request->good_id;
        $goods_num = $request->num;

        $validator = validator($request->all(),
            ['good_id' => 'required', 'num' => 'numeric|min:1'], [
                'num.numberic' => '数量格式不正确',
                'num.min' => '最小值为1',
            ]);
        if ($validator->fails()) {
            $error = $validator->errors();
            foreach ($error->all() as $message) {
                $return['message'] = $message;
                return Response()->json($return);
            }
        }
        try {
            $cartService->addGoods($goods_id, $goods_num);
            //$cartInfo = $cartService->getInfo();
            //$return['goods_num'] = $cartInfo['total_number'];

            $cartNum = $cartService->getCartNumber();
            $return['code'] = 1;
            $return['goods_num'] = $cartNum;

        } catch (InvalidArgumentException $e) {

            $return['message'] = $e->getMessage();

        }//end try

        return Response()->json($return);
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }
    public function update(Request $request,CartService $cartService){

        $goods_id=$request->good_id;
        $num=$request->num;
        $cartService->updateGoods($goods_id,$num);
        $return = ['message' => '', 'code' => 0];

        $cartNum = $cartService->getCartNumber();
        $return['code'] = 1;
        $return['goods_num'] = $cartNum;
        return Response()->json($return);
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     * @return \Illuminate\Http\Response
     */
    public function destroy(CartService $cartService, Request $request)
    {

        $return = ['status' => 1, 'message' => '删除成功', 'data' => ''];

        $goods_ids = $request->goods_ids;

        if (empty($goods_ids)) {

            $return['message'] = '要删除的商品id数组不能为空';

            return Response()->json($return);
        } else {

            try {

                $cartService->removeGoods($goods_ids);

            } catch (InvalidArgumentException $e) {

                $return['message'] = $e->getMessage();
            }//end try
        }//end if()

        return Response()->json($return);
    }


    /**
     * 获取商品数组中商品总数、总价、总关税等信息
     *
     * @param array $sel_id : 当前更改的商品id
     *
     * @return mixed 1. 总价,总个数,总关税,更改的商品关税  {"total_number":3,"total_price":"2204.77","total_tariff_price":"222.81","tariff_price":199.9}
     */
    public function getGoodsInfo($goods_id, CartService $cartService, Request $request, GoodsService $goodsService)
    {

        $return = ['status' => 1, 'message' => '', 'data' => ''];

        $cartGoods = $request->get('cartGoods');

        $buy_num = 0;

        foreach ($cartGoods as $key => $value) {

            /*if ($goods_id==$v['goods_id']){

                $buy_num = $v['buy_num'];
            }*/

            try {

                // $cartService->updateNumber($goods_id,$buy_num);
                $cartService->updateNumber($value['goods_id'], $value['buy_num']);

            } catch (CartServiceException $e) {

                $goods_name = Goods::where('goods_id', $value['goods_id'])->pluck('goods_name');

                $return['status'] = 0;

                $return['message'] = $goods_name . $e->getMessage();

                return response()->json($return);
            }
        }

        $cart = $cartService->getGoodsInfo($cartGoods);

        return response()->json(['info' => $cart]);

    }//end func getGoodsInfo


}
